<?php
class CPage extends CRecord
{
	static $current = false;
	static $drawing = false;
	static $edit_mode = false;
	static $default_page = 'home';
	public $all_blocks = array();
	public $params = array();
	static $max_module_id = 0;

	/**
	 * data từ đâu ra???
	 *
	 * @param unknown_type $data
	 */
	function __construct($data) {
//		echo "<pre>";
//		print_r(portal());
//		die;
		parent::__construct($data);
		CPage::$max_module_id = intval(request('module_id'));
		$portal = portal();

		if(DEBUG) {
			$modules = 'vhv_all_modules='.CPage::get_modules_js().';';
			if(!is_dir('publish/'.$portal->id)) {
				mkdir('publish/'.$portal->id);
			}
			if(DEBUG and !CFile::exists('publish/'.$portal->id.'/modules.js') or file_get_contents('publish/'.$portal->id.'/modules.js') != $modules) {
				file_put_contents('publish/'.$portal->id.'/modules.js', $modules);
			}
		}
		$this->params = array(
			'keywords' => $portal->setting('keywords'),
			'title' => $portal->setting('title'),
			'description' => $portal->setting('description'),
			'links' => '',
			'user_id'=>session('user_id')?session('user_id'):'guest',
			'is_admin'=>user()->is_admin()?'true':'false',
			'is_debug'=>DEBUG?'true':'false',
			'portal_id' => $portal->id,
			'root_url' => CPortal::$root_url,
			'static_url' => CPortal::$static_url,
			'meta_description' => $portal->setting('meta_description'), //blacknight's test
			'meta_keywords' => $portal->setting('meta_keywords'),
			'useChat' => true,			
			'image_src' => $portal->setting('image_src'),			
			'ignore_js' => array('quick_sale', 'admin', 'multi_quick_sale', 'partner_quick_sale'),
		);
	}

	function submit() {
		//Khoanb Edit 25.05.2009
		if(request('submit_form_id')) {
			foreach($this->all_blocks as &$block) {
				if(isset($block->id) and intval(request('submit_form_id')) == intval($block->id)) {
					$last = &CModule::$current;
					CModule::$current = &$block;
					$block->submit();
					CModule::$current = &$last;
				}
			}
		}
		CPage::$drawing = true;
	}

	static function load($page = false) {
		$module = request('module');
		if(!$page or is_int($page)) {
			if($module) {
			  $pagename = request('page');
				if($pagename and !is_numeric($pagename)) {
					$page = CPage::get_current_page(portal()->data);
					if($page['name'] == $pagename) {
						$cache_name = CSystem::$layout_cache_dir.$pagename.'.'.$page['params'].'.'.$module.'.php';
						if(DEBUG or !file_exists($cache_name)) {
							require_once ROOT_DIR.'lib/utils/CPageCache.php';							
							$page_cache = new CPageCache($page, $module);
							$contentCache = $page_cache->cache($cache_name);
							if(@COMPRESS_HTML){
								require_once ROOT_DIR.'lib/utils/CMinifyHTML.php';
								$contentCache = CMinifyHTML::minify($contentCache);
							}										
							file_put_contents($cache_name, $contentCache);
						}
						require_once($cache_name);
						echo '<script type="text/javascript">'.portal()->script.'</script>';
						return;
					}
				} else {
					$cache_name = CSystem::$layout_cache_dir.$module.'.php';
					if(DEBUG or !file_exists($cache_name)) {
						require_once ROOT_DIR.'lib/utils/CPageCache.php';
						$page_cache = new CPageCache('', $module);
						$contentCache = $page_cache->cache($cache_name);
						if(@COMPRESS_HTML){
							require_once ROOT_DIR.'lib/utils/CMinifyHTML.php';
							$contentCache = CMinifyHTML::minify($contentCache);
						}
						file_put_contents($cache_name, $contentCache);
					}
					require_once($cache_name);
					echo '<script type="text/javascript">'.portal()->script.'</script>';
					return;
				}
				return;
			}
			$page = CPage::get_current_page(portal()->data);
			
		}
		if($page) {
		
		  $cache_name = CSystem::$layout_cache_dir.$page['name'].'.'.$page['params'].'.php';
		  if (DEBUG or !file_exists($cache_name)) {
		    require_once ROOT_DIR.'lib/utils/CPageCache.php';
			$page_cache = new CPageCache($page, false);
			$contentCache = $page_cache->cache($cache_name);
			if(@COMPRESS_HTML){
				require_once ROOT_DIR.'lib/utils/CMinifyHTML.php';
				$contentCache = CMinifyHTML::minify($contentCache);
			}			
			file_put_contents($cache_name, $contentCache);
			//file_put_contents($cache_name, $page_cache->cache($cache_name));
		  } 
			require_once($cache_name);
			if(defined('EXPORT_JS_AND_CSS') and CPage::$current->name != 'run_by_module') {
				echo '
				<script type="text/javascript">
					$(function(){
						setTimeout(function(){
							SYS.makeLinksCache(\''.request('page', CPage::$current->name).'\');
						},1000);
					});
				</script>
				';
			}
		}
	}
	static function get_current_page($portal_data, $page_name = false, $use_default_portal = false) {
		if(!$page_name) {
			$page_name = request('page', CPage::$default_page);
		}
		if(!($pages = CList(CList(CPortal::$components)->filter(array('type'=>'PAGE', 'name'=>$page_name)))->order('params desc')->items)) {
			$pages =  CList(CList(CPortal::$components)->filter(array('type'=>'PAGE', 'name'=>CPage::$default_page)))->order('params desc')->items;
		}

		if(isset($portal_data['name'])) {
			$portal_name = $portal_data['name'];
		} else {
			return self::get_current_page(CPortal::get_data(CPortal::$default), CPage::$default_page);
		}
		if($pages) {
			foreach($pages as $page) {
				if($page['portal'] == $portal_name) {
					if($page['params']=='') {
						return $page;
					} else {
						$params = explode('&',$page['params']);
						$ok = true;
						foreach($params as $param) {
							if($param = explode('=',$param)) {
								if(sizeof($param)==1) {
									if(!CUrl::check($param[0])) {
										$ok = false;
										break;
									}
								} elseif($param[0]=='portal') {
									if($param[1] != $portal_name) {
										$ok = false;
										break;
									}
								} elseif(request($param[0])!=$param[1]) {
									$ok = false;
									break;
								}
							}
						}
						if($ok) return $page;
					}
				}

			}
			if($portal_data['parent'])
				return CPage::get_current_page(CPortal::get_data($portal_data['parent']), $page_name);
			return reset($pages);
		}
	}

	static function params($key) {
		if(isset(CPage::$current) and isset(CPage::$current->params[$key]))
			return CPage::$current->params[$key];
	}

	function link($code) {
		if(strpos($this->params['links'],$code) === false) {
			$this->params['links'] .= $code;
			if(CPage::$drawing) echo $code;
		}
	}

	function js($file) {
		$this->link('<script type="text/javascript" src="'.$file.'"></script>');
	}

	function css($file) {
		$this->link('<link href="'.$file.'" media="screen" rel="stylesheet" type="text/css"/>');
	}

	function region($region) {
		$parent_id = CModule::$current?CModule::$current->id:-1;
		foreach($this->all_blocks as $id => &$block) {
			if($block and $block->parent_id == $parent_id and $block->region == $region) {
				$last = &CModule::$current;
				CModule::$current = &$this->all_blocks[$id];
				CModule::$current->draw();
				CModule::$current = &$last;
			}
		}
	}

	static function get_modules_js() {
		$modules = array();
		$all_modules = CList(CPortal::$components)->filter(array('type'=>'MODULE'));
		foreach($all_modules as $module) {
			$modules[$module['name']] = array(
				'path' => $module['path'],
			);
		}
		return CString($modules)->json();
	}
}

function CPage($id, $blocks = array()) {
	return new CPage($id, $blocks);
}

function region($region) {
	CPage::$current->region($region);
}


